<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" v-model="name" />
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model="age" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="sex">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="add">{{text}}</button>
    </div>
    <div>
      <table border="1" cellpadding="10" cellspacing="0">
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(item,index) in list" :key="index.id">
          <td>{{index+1}}</td>
          <td>{{item.name}}</td>
          <td>{{item.age}}</td>
          <td>{{item.sex}}</td>
          <td>
            <button @click="del(item.id)">删除</button>
            <button @click="edit(item,index)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  //侦听数组变化
  watch: {
    list: {
      handler() {
        localStorage.setItem('score-case', JSON.stringify(this.list))
      },
      deep: true,
    },
  },
  data() {
    return {
      list: JSON.parse(localStorage.getItem('score-case')) || [
        { id: 1, name: '小陈', age: 20, sex: '女' },
        { id: 2, name: '小杨', age: 22, sex: '女' },
      ],
      name: '',
      age: '',
      sex: '',
      text: '添加',
      data: true,
      obj: {},
    }
  },
  methods: {
    // 编辑按钮
    edit(item, i) {
      this.name = item.name
      this.age = item.age
      this.sex = item.sex
      this.obj = {
        id: item.id,
        index: i,
      }
      this.data = false
      this.text = '确认修改'
    },

    // 添加按钮
    add() {
      if (this.data === true) {
        if (this.name !== '' && this.age > 0) {
          this.list.push({
            id: Date.now(),
            name: this.name,
            age: this.age,
            sex: this.sex,
          })
          this.name = ''
          this.age = ''
          this.sex = ''
        } else if (this.name === '' || this.age === '') {
          alert('请输入合法字符')
        }
      } else {
        this.data = true
        this.text = '添加'
        this.list[this.obj.index] = {
          id: this.obj.id,
          name: this.name,
          age: this.age,
          sex: this.sex,
        }
        this.name = ''
        this.age = ''
        this.sex = ''
      }
    },
    // 删除按钮
    del(id) {
      this.list=this.list.filter(ele =>ele.id !== id)
    },
  },
}
</script>
